// 弹窗复选
import React, { useEffect } from 'react';
import { Button } from 'antd';
import moment from 'moment';
import * as XLSX from 'xlsx';

import { FileList } from './components/fileList.jsx';
// @ts-ignore
import { UploadOutlined } from '#/utils/antdIcons';
// @ts-ignore
import { TJModel, TjSelect } from '@/pages/ETrade/components';
// @ts-ignore
import Message from '#/components/Message';
import tAlert from '#/components/Alert/index.js';
import { HttpCode } from '#/utils/contacts.js';
// @ts-ignore
import { useTRState } from '#/utils/trHooks';

import { postInsertContract } from '../../service';
import { excelMap, timeSliceObjType } from '../../dictionary';
import styles from './index.less';

const initValue = {
  visible: false,
  fileError: true,
  showBtn: true,
  uploadData: {},
  finalyFile: [],
  station: null,
  start: false,
  percent: 0,
  btnLoding: false,
  uploadList: [],
};
const ExportBtn = (props: any) => {
  const { disabled, stationOptions, form } = props;
  const [state, setState] = useTRState(initValue);

  useEffect(() => {
    if (state.visible) {
      let arr = stationOptions || [];
      arr = arr?.map((i: any) => ({ ...i, status: 'upload' }));
      setState({
        uploadList: arr,
      });
    }
  }, [stationOptions, state.visible]);

  const _onCancel = () => {
    setState(initValue);
  };

  const getProgress = () => {
    let temp = 0;
    return setInterval(() => {
      temp++;
      setState({
        percent: Math.floor((1 - 100 / (100 + temp)) * 100),
      });
    }, 10);
  };

  const _onOk = async () => {
    const promiseArr = [];
    for (const key in state.uploadData) {
      promiseArr.push(postInsertContract({ param: state.uploadData[key] }));
    }
    if (state.btnLoding) return;
    setState({
      start: true,
      percent: 0,
      btnLoding: true,
    });
    const timer = getProgress();
    // @ts-ignore
    const allData = Promise.all(promiseArr);
    allData.then((res: any) => {
      const status = res?.filter((v: any) => v.statusCode !== HttpCode.SUCCESS);
      if (status.length === 0) {
        tAlert.Success(res?.[0]?.message || '导入成功');
        form.submit();
        _onCancel();
      } else {
        tAlert.error(res?.[0]?.message || '导入失败');
      }
      clearInterval(timer);
      setState({
        percent: 100,
        btnLoding: false,
      });
    });
  };

  const onImport = () => {
    if (disabled) return Message.info('请联系管理员获取相关权限');
    setState({
      visible: true,
      fileError: true,
    });
  };

  const setUploadError = (stationId: any, message: string, fileName: string) => {
    const arr = state.uploadList.map((i: any) =>
      i.value === stationId ? { ...i, status: 'error', message, fileName } : i,
    );
    setState({
      uploadList: arr,
    });
  };

  const _deleteUploadFile = (stationId: any) => {
    const newUploadList = state.uploadList.map((i: any) =>
      i.value === stationId
        ? {
            ...i,
            fileList: [],
            fileName: '',
            status: 'upload',
          }
        : i,
    );
    const newUploadData = state.uploadData;
    delete newUploadData[stationId];
    setState({
      uploadList: newUploadList,
      uploadData: newUploadData,
    });
  };

  const _beforeUpload = (file: any, stationId: any) => {
    setState({
      btnLoding: true,
      fileError: true,
    });
    // 通过FileReader对象读取文件
    const fileReader = new FileReader();
    fileReader.onload = async (event) => {
      const errLine: number[] = [];
      const { result }: any = event.target;
      // 以二进制流方式读取得到整份excel表格对象
      const workbook = XLSX.read(result, { type: 'binary', header: 1 });
      const _finalyFile: any = [];
      for (const sheet in workbook.Sheets) {
        const _temp = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);

        if (!_temp?.[0]) {
          setState({
            fileError: false,
            btnLoding: false,
          });
          setUploadError(stationId, '模板有误', file.name);
          return false;
        }
        _temp.forEach((colData: any, index: number) => {
          if (!(colData['合同名称'] && colData['合同编号'] && colData['月份'])) {
            errLine.push(index + 1);
          }
          const temp: any = {};
          Object.entries(colData).forEach((t: any) => {
            const key = excelMap[t[0]];
            if (!key) return; //字典中未录入的字段
            let value = t[1] ?? '';
            if (key === 'month') {
              value = moment(value).startOf('M').format('YYYY-MM-DD');
            }
            if (key === 'powerSourceType') {
              value = value;
            }
            temp[key] = value;
          });
          temp.stationId = stationId;
          temp.stationName = stationOptions.find((t: any) => t.value === stationId).label;
          _finalyFile.push(temp);
        });
      }
      if (errLine.length !== 0) {
        setUploadError(stationId, '存在错误合约信息', file.name);
        setState({
          btnLoding: false,
        });
        return false;
      }
      const uploadData = state.uploadData;
      uploadData[stationId] = _finalyFile;
      setState({
        btnLoding: false,
        uploadData,
      });
    };
    // 以二进制方式打开文件
    fileReader.readAsBinaryString(file);
    return false;
  };

  const _uploadChange = (info: any, stationId: any) => {
    if (info.fileList.length) {
      setState({
        showBtn: false,
      });
    } else {
      const uploadData = state.uploadData;
      delete uploadData[stationId];
      setState({
        uploadData,
        showBtn: true,
        start: false,
      });
    }
    const arr = state.uploadList.map((i: any) =>
      i.value === stationId
        ? {
            ...i,
            fileList: info.fileList || [],
            fileName: info.file.name,
            status: 'success',
          }
        : i,
    );
    setState({
      uploadList: arr,
    });
  };
  const { visible, btnLoding, uploadData } = state;
  return (
    <>
      <Button
        style={{ padding: 0 }}
        className={`${disabled && styles.disabled}`}
        type="link"
        icon={<UploadOutlined />}
        onClick={onImport}
      >
        导入
      </Button>
      {visible && (
        <TJModel
          title={'导入'}
          visible={true}
          style={{ alignItems: 'center !important' }}
          onCancel={_onCancel}
          footer={[
            <Button key="back" onClick={_onCancel}>
              取消
            </Button>,
            Object.keys(uploadData).length !== 0 && (
              <Button key="submit" type="primary" loading={btnLoding} onClick={_onOk}>
                导入
              </Button>
            ),
          ]}
        >
          <FileList
            uploadList={state.uploadList}
            beforeUpload={_beforeUpload}
            uploadChange={_uploadChange}
            deleteUploadFile={_deleteUploadFile}
            btnLoding={btnLoding}
          />
        </TJModel>
      )}
    </>
  );
};

export default ExportBtn;
